const commonConfig = require('./webpack.common')
const {merge} = require('webpack-merge')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const path = require('path')
const {DefinePlugin} = require('webpack')
const WebpackDevServer = require('webpack-dev-server')
const webpack = require('webpack')

const devServerRun = () => {
    const config = merge(commonConfig, {
        mode: 'development',
        devtool: 'source-map',
        plugins: [
            new HtmlWebpackPlugin({
                filename: 'index.html',
                title: 'Webpack-Vue-Demo',
                template: './public/index.html',
                hash: true,
                favicon: path.resolve('./public/favicon.ico')
            }),
            new DefinePlugin({
                BASE_URL: '"./"'
            })
        ]
    })
    const options = {
        hot: true,
        compress: true,		// 开发服务器启用gzip压缩
        progress: true,		// 控制台显示打包进度
        open: true, 		// 自动打开浏览器
        overlay: true,       // 出现编译器错误或警告时，在浏览器中显示全屏覆盖
        proxy: {
            '/api': {           // 请求路径前缀
                // http://localhost:8080/api/users  --> https://api.github.com/api/users
                target: 'https://api.github.com',
                // http://localhost:8080/api/users  --> https://api.github.com/users
                pathRewrite: {
                    '^/api': ''
                },
                // 不能使用 localhost:8080 作为请求 github 的主机名
                changeOrigin: true
            }
        }
    }

    WebpackDevServer.addDevServerEntrypoints(config, options)   // HMR 入口起点
    const compiler = webpack(config)
    new WebpackDevServer(compiler, options).listen(8080, 'localhost', err => {
        if(err) console.log(err)
    })
}

devServerRun()
